package com.cndongtai.controller.device;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cndongtai.constant.LightConstant;
import com.cndongtai.constant.UserConstant;
import com.cndongtai.controller.BaseController;
import com.cndongtai.po.Dtu;
import com.cndongtai.po.DtuStatus;
import com.cndongtai.po.Light;
import com.cndongtai.po.LightConfig;
import com.cndongtai.po.User;
import com.cndongtai.service.light.DtuService;
import com.cndongtai.service.light.LightService;
import com.cndongtai.service.net.NetService;
import com.cndongtai.util.DateUtil;
import com.cndongtai.util.ValidateUtil;
import com.cndongtai.vo.LightBean;
import com.cndongtai.vo.LightConfigBean;
import com.cndongtai.vo.LightStatusBean;

@Controller
public class DeviceController extends BaseController {
	 
	@Resource(name="dtuService")
	private DtuService dtuService;
	
	@Resource(name="netService")
	private NetService netService;
	
	@Resource(name="lightService")
	private LightService lightService;
	
	@RequestMapping("/showDevice")
	public String showDevice() {
		User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		
		String lightOn = getMessage("install.light.status.on",null);
		String lightDown = getMessage("install.light.status.off",null);
		String online = getMessage("install.net.status.online",null);
		String offline = getMessage("install.net.status.offline",null);
		
		if("admin".equals(user.getUsername())) {
			String jsonTree = dtuService.getDeviceJsonTree(lightOn, lightDown, online, offline);
			request.setAttribute("jsonTree", jsonTree);
			request.setAttribute("isAdmin", true);
		}else {
			String jsonTree = dtuService.getDeviceJsonTree(user.getUserId(),lightOn, lightDown, online, offline);
			request.setAttribute("jsonTree", jsonTree);
			request.setAttribute("isAdmin", false);
		}
		
		return "device/deviceMgr";
	}
	
	@RequestMapping("/beforeAddDtu")
	public String beforeAddDtu() {
		
		return "device/addDtu";
	}

	@RequestMapping("/addDtu")
	@ResponseBody
	public void addDtu() {
		JSONObject result = new JSONObject();
		
		String dtuName = this.getValue("dtuName");
		String panId = this.getValue("panId");
		String longitude = this.getValue("longitude");
		String latitude = this.getValue("latitude");
		String dtuType = this.getValue("dtuType");
		
		User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);

		Double longitudeDou = null;
		Double latitudeDou = null;
		try {
			longitudeDou = Double.parseDouble(longitude);
			latitudeDou = Double.parseDouble(latitude);
		}catch (Exception e) {
			result.put("success", 1);
			result.put("msg", getMessage("dtu.add.msg.lnglaterror",null));
			this.writeData(result);
			return;
		}
		
		if(longitudeDou<-180 || longitudeDou>180) {
			result.put("success", 1);
			result.put("msg", getMessage("dtu.add.msg.lnglaterror",null));
			this.writeData(result);
			return;
		}
		
		if(latitudeDou<-90 || latitudeDou>90) {
			result.put("success", 1);
			result.put("msg", getMessage("dtu.add.msg.lnglaterror",null));
			this.writeData(result);
			return;
		}
		
		Object[] res = dtuService.addDtu(dtuName, panId, longitudeDou, latitudeDou, user.getUserId(),Integer.valueOf(dtuType));

		//netService.getLightByPanId(panId);
		//netService.turnonLight(panId, "1113",1000,1);
		//netService.shutDownLight(panId, "1113");
		//netService.checkTime(panId, "1113");
		//netService.readRtuConfig(panId, "1113");
		//netService.readRtuStatus(panId, "1113");
		//netService.readDtuStatus(panId);
		//netService.rtuConfig(panId, "1113");
		
		if((boolean) res[0]) {
			result.put("success", 0);
		}else {
			result.put("success", 1);
		}
		
		result.put("msg", getMessage(res[1].toString(),null));
		this.writeData(result);
	}
	
	
	@RequestMapping("/updateDtuLocation")
	@ResponseBody
	public void updateDtuLocation() {
		JSONObject result = new JSONObject();
		
		String panId = this.getValue("panId");
		String longitude = this.getValue("longitude");
		String latitude = this.getValue("latitude");
		
		Double longitudeDou = null;
		Double latitudeDou = null;
		try {
			longitudeDou = Double.parseDouble(longitude);
			latitudeDou = Double.parseDouble(latitude);
		}catch (Exception e) {
			result.put("success", 1);
			result.put("msg", "请检查手机网络及定位，重新扫描二维码");
			this.writeData(result);
			return;
		}
		
		if(longitudeDou>136 || longitudeDou<70) {
			result.put("success", 1);
			result.put("msg", "经纬度偏差太大，请重扫描二维码");
			this.writeData(result);
			return;
		}
		
		if(latitudeDou>55 || latitudeDou<0) {
			result.put("success", 1);
			result.put("msg", "经纬度偏差太大，请重请重扫描二维码");
			this.writeData(result);
			return;
		}
		
		Object[] res = dtuService.updateDtuLocation(panId, longitudeDou, latitudeDou);
		
		if((boolean) res[0]) {
			result.put("success", 0);
		}else {
			result.put("success", 1);
		}
		
		result.put("msg", res[1]);
		this.writeData(result);
	}
	
	@RequestMapping("/beforeAddLight")
	@ResponseBody
	public void beforeAddLight() {
		JSONObject result = new JSONObject();
		String deviceId = this.getValue("deviceId");
		String dtuId = deviceId.substring(4);
		
		Dtu dtu = dtuService.queryDtuById(dtuId);
		
		List<Light> lightList = lightService.queryLightListByDtuId(dtuId);
		List<LightBean> lightBeanList = netService.getLightByPanId(dtu.getPanId());
		
		if(lightBeanList==null) {
			lightBeanList =  new ArrayList<LightBean>();
		}
		
		/*LightBean bb = new LightBean();
		bb.setLightNum("1113");
		lightBeanList.add(bb);
		
		LightBean cc = new LightBean();
		cc.setLightNum("1114");
		lightBeanList.add(cc);*/
		
		if(lightBeanList==null || lightBeanList.size()==0) {
			result.put("success", "1");
			this.writeData(result);
			return;
		}
		
		if(lightList==null || lightList.size()==0) {
			result.put("success", "0");
			result.put("resultdata", lightBeanList);
			this.writeData(result);
			return;
		}
		
		List<LightBean> lightBeanListNew = new ArrayList<LightBean>();
		for(LightBean lightBean : lightBeanList) {
			boolean flag = true;
			for(Light light : lightList) {
				if(lightBean.getLightNum().equals(light.getLightNum())) {
					flag = false;
					break;
				}
			}
			if(flag) {
				lightBeanListNew.add(lightBean);
			}
		}
		
		if(lightBeanListNew.size()==0) {
			result.put("success", "1");
			this.writeData(result);
			return;
		}
		
		result.put("success", "0");
		result.put("resultdata", lightBeanListNew);
		this.writeData(result);
	}
	
	@RequestMapping("/delDevice")
	@ResponseBody
	public void delDevice() {
		JSONObject result = new JSONObject();
		
		String deviceId = this.getValue("deviceId");
		if(ValidateUtil.empty(deviceId)) {
			result.put("success", 1);
			result.put("msg", "该设备不存在");
			this.writeData(result);
			return;
		}

		boolean res = false;
		if(deviceId.startsWith("dtu_")) {
			// 删除DTU
			res = dtuService.delDtu(deviceId.substring(4));
		}else {
			// 删除Light
			res = lightService.delLight(deviceId);
		}
		
		if(res) {
			result.put("success", "0");
			result.put("msg", "删除成功");
		}else {
			result.put("success", "1");
			result.put("msg", "删除失败");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/shutdownLight")
	@ResponseBody
	public void shutdownLight() {
		JSONObject result = new JSONObject();
		
		String deviceId = this.getValue("deviceId");
		if(ValidateUtil.empty(deviceId)) {
			result.put("success", 1);
			result.put("msg", "该设备不存在");
			this.writeData(result);
			return;
		} 
		
		boolean res = false;
		if(deviceId.startsWith("dtu_")) {
			// 根据DTU关灯
			Dtu dtu = dtuService.queryDtuById(deviceId.substring(4));
			if(dtu.getDtuType()==0) {
				res = netService.shutDownLight(dtu.getPanId(), null);
				if(res) {
					dtuService.changeLightState(dtu.getDtuId(), LightConstant.LIGHT_STATE_OFF);
				}
			}else {
				// 获取下面的设备
				List<Light> lightList = lightService.queryLightListByDtuId(dtu.getDtuId()+"");
				for(Light light : lightList) {
					res = netService.shutDownLight(dtu.getPanId(), light.getLightNum());
					if(res) {
						lightService.changeLightState(light.getLightId(), LightConstant.LIGHT_STATE_OFF);
					}
				}
				
				// 修改集中器开关灯状态
				dtuService.changeLightState(dtu.getDtuId(), LightConstant.LIGHT_STATE_OFF);
			}
		}else {
			// 关闭指定Light
			Light light = lightService.queryLightById(deviceId);
			Dtu dtu = dtuService.queryDtuById(light.getDtuId()+"");
			res = netService.shutDownLight(dtu.getPanId(), light.getLightNum());
			if(res) {
				lightService.changeLightState(light.getLightId(), LightConstant.LIGHT_STATE_OFF);
			}
		}
		
		if(res) {
			result.put("success", "0");
			result.put("msg", "关闭成功");
		}else {
			result.put("success", "1");
			result.put("msg", "网络异常");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/turnonLight")
	@ResponseBody
	public void turnonLight() {
		JSONObject result = new JSONObject();
		
		String deviceId = this.getValue("deviceId");
		if(ValidateUtil.empty(deviceId)) {
			result.put("success", 1);
			result.put("msg", "该设备不存在");
			this.writeData(result);
			return;
		}
		
		String workCurrent = this.getValue("workCurrent");
		String minute   = this.getValue("minute");
		
		boolean res = false;
		if(deviceId.startsWith("dtu_")) {
			// 根据DTU开灯
			Dtu dtu = dtuService.queryDtuById(deviceId.substring(4));
			
			if(dtu.getDtuType()==0) {
				res = netService.turnonLight(dtu.getPanId(), null,Integer.valueOf(workCurrent), Integer.valueOf(minute));
				// 更新状态
				if(res) {
					dtuService.changeLightState(dtu.getDtuId(), LightConstant.LIGHT_STATE_ON);
				}
			}else {
				// 获取下面的设备
				List<Light> lightList = lightService.queryLightListByDtuId(dtu.getDtuId()+"");
				for(Light light : lightList) {
					res = netService.turnonLight(dtu.getPanId(), light.getLightNum(),Integer.valueOf(workCurrent), Integer.valueOf(minute));
					if(res) {
						lightService.changeLightState(light.getLightId(), LightConstant.LIGHT_STATE_ON);
					}
				}
				
				// 修改集中器开关灯状态
				dtuService.changeLightState(dtu.getDtuId(), LightConstant.LIGHT_STATE_ON);
			}
		}else {
			// 打开指定Light
			Light light = lightService.queryLightById(deviceId);
			Dtu dtu = dtuService.queryDtuById(light.getDtuId()+"");
			res = netService.turnonLight(dtu.getPanId(), light.getLightNum(),Integer.valueOf(workCurrent), Integer.valueOf(minute));
			if(res) {
				lightService.changeLightState(light.getLightId(), LightConstant.LIGHT_STATE_ON);
			}
		}
		
		if(res) {
			result.put("success", "0");
			result.put("msg", "开灯成功");
		}else {
			result.put("success", "1");
			result.put("msg", "网络异常,该设备不在线");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/addLight")
	@ResponseBody
	public void addLight() {
		JSONObject result = new JSONObject();
		String dtuId = this.getValue("dtuId");
		dtuId = dtuId.substring(4);
		
		String lightNums = this.getValue("lightNums");
		String longitudes = this.getValue("longitudes");
		String latitudes = this.getValue("latitudes");
		
		if(ValidateUtil.empty(lightNums)) {
			result.put("success", "1");
			result.put("msg", "请选择要添加的路灯");
			this.writeData(result);
			return;
		}
		
		String[] lightNumArr = lightNums.split(",");
		String[] longitudeArr = longitudes.split(",");
		String[] latitudeArr = latitudes.split(",");
		
		System.out.println("dtuId:"+dtuId + "lightNumArr:" +lightNumArr);
		
		if(lightNumArr==null || lightNumArr.length==0) {
			result.put("success", 1);
			result.put("msg", "请选择要添加的路灯");
			this.writeData(result);
			return;
		}
		
		if(lightNumArr.length!=longitudeArr.length || lightNumArr.length!=latitudeArr.length) {
			result.put("success", 1);
			result.put("msg", "请选择要添加的路灯");
			this.writeData(result);
			return;
		}
		
		Double[] longitudeArrD = new Double[lightNumArr.length];
		Double[] latitudeArrD = new Double[lightNumArr.length];
		for(int i=0;i<lightNumArr.length;i++) {
			String lightNum = lightNumArr[i];
			// 获取经纬度
			try {
				longitudeArrD[i] = Double.valueOf(longitudeArr[i]);
				latitudeArrD[i] = Double.valueOf(latitudeArr[i]);
			}catch(Exception e) {
				result.put("success", 1);
				result.put("msg", "路灯编号为"+lightNum+"的经纬度填写错误，请检查确认后再提交");
				this.writeData(result);
				return;
			}
		}
		
		User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);
		
		Object[] res = lightService.addLights(dtuId, lightNumArr, longitudeArrD, latitudeArrD, user.getUserId());
		if((boolean) res[0]) {
			result.put("success", 0);
			result.put("msg", "添加成功");
		}else {
			result.put("success", 1);
			result.put("msg", res[1].toString());
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/addLightNew")
	@ResponseBody
	public void addLightNew() {
		// 做数据校验
		JSONObject result = new JSONObject();
		String key = this.getValue("method");
		String panId = this.getValue("panId");
		String lightNum = this.getValue("lightNum");
		String longitude = this.getValue("longitude");
		String latitude = this.getValue("latitude");

		if(ValidateUtil.empty(lightNum) 
				|| ValidateUtil.empty(panId)
				|| ValidateUtil.empty(longitude)
				|| ValidateUtil.empty(latitude)) {
			result.put("success", "1");
			result.put("msg", "添加失败(0001)！");
			this.writeData(result);
			return;
		}
		
		if(lightNum.length()!=4 || panId.length()!=4) {
			result.put("success", "1");
			result.put("msg", "添加失败(0002)！");
			this.writeData(result);
			return;
		}
		
		Dtu dtu = dtuService.queryDtuByPanId(panId);
		if(dtu == null) {
			result.put("success", "1");
			result.put("msg", "网络设备不存在，添加失败！");
			this.writeData(result);
			return;
		}
		
		Double longitudeArrD = Double.valueOf(longitude);
		Double latitudeArrD = Double.valueOf(latitude);
		
		/*User user = (User) request.getSession().getAttribute(UserConstant.SESSION_USER);*/
		
		Object[] res = lightService.addLight(dtu.getDtuId()+"", lightNum, longitudeArrD, latitudeArrD);
		if((boolean) res[0]) {
			result.put("success", 0);
			result.put("msg", res[1].toString());
		}else {
			result.put("success", 1);
			result.put("msg", res[1].toString());
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/changeLocation")
	@ResponseBody
	public void changeLocation() {
		// 做数据校验
		JSONObject result = new JSONObject();
		String deviceId = this.getValue("deviceId");
		String mlat = this.getValue("mlat");
		String mlng = this.getValue("mlng");
		if(deviceId.startsWith("dtu_")) {
			Object[] res = dtuService.updateDtuLocationById(Integer.valueOf(deviceId.substring(4)), mlng, mlat);
			if((boolean) res[0]) {
				result.put("success", 0);
				result.put("msg", res[1].toString());
			}else {
				result.put("success", 1);
				result.put("msg", res[1].toString());
			}
		}else {
			Object[] res = lightService.changeLocation(Integer.valueOf(deviceId), mlat, mlng);
			if((boolean) res[0]) {
				result.put("success", 0);
				result.put("msg", res[1].toString());
			}else {
				result.put("success", 1);
				result.put("msg", res[1].toString());
			}
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/queryLocation")
	@ResponseBody
	public void queryLocation() {
		// 做数据校验
		JSONObject result = new JSONObject();
		String deviceId = this.getValue("deviceId");
		
		if(deviceId.startsWith("dtu_")) {
			Dtu dtu = dtuService.queryDtuById(deviceId.substring(4));
			if(dtu!=null) {
				result.put("success", 0);
				result.put("lat", dtu.getLatitude());
				result.put("lng", dtu.getLongitude());
			}else {
				result.put("success", 1);
				result.put("msg", "该设备不存在");
			}
		}else {
			Light light = lightService.queryLightById(deviceId);
			if(light!=null) {
				result.put("success", 0);
				result.put("lat", light.getLatitude());
				result.put("lng", light.getLongitude());
			}else {
				result.put("success", 1);
				result.put("msg", "该设备不存在");
			}
		}
		
		this.writeData(result);
	}
	
	
	@RequestMapping("/readDtuStatus")
	@ResponseBody
	public void readDtuStatus() {
		JSONObject result = new JSONObject();
		
		String deviceId = this.getValue("deviceId");
		if(ValidateUtil.empty(deviceId)) {
			result.put("success", 1);
			result.put("msg", "该设备不存在！");
			this.writeData(result);
			return;
		}
		
		if(deviceId.startsWith("dtu_")) {
			Dtu dtu = dtuService.queryDtuById(deviceId.substring(4));
			if(dtu==null) {
				result.put("success", 1);
				result.put("msg", "该设备不存在！");
				this.writeData(result);
				return;
			}
			
			DtuStatus dtuStatus = netService.readDtuStatus(dtu.getPanId());
			if(dtuStatus==null) {
				result.put("success", 1);
				result.put("msg", "设备状态查看失败，可能因为网络波动，稍后请重试！");
			}else {
				if("00".equals(dtuStatus.getStatus())) {
					dtuStatus.setStatus("正常");
				}else if("01".equals(dtuStatus.getStatus())) {
					dtuStatus.setStatus("Zigbee模块异常");
				}else if("02".equals(dtuStatus.getStatus())) {
					dtuStatus.setStatus("电源电压异常");
				}else if("03".equals(dtuStatus.getStatus())) {
					dtuStatus.setStatus("集中器温度异常");
				}
				
				result.put("success", 0);
				result.put("dtu", dtu);
				result.put("dtuStatus", dtuStatus);
			}
		}else {
			result.put("success", 1);
			result.put("msg", "该设备不存在！");
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/readLightStatus")
	@ResponseBody
	public void readLightStatus() {
		JSONObject result = new JSONObject();
		String deviceId = this.getValue("deviceId");
		if(ValidateUtil.empty(deviceId)) {
			result.put("success", 1);
			result.put("msg", "该设备不存在！");
			this.writeData(result);
			return;
		}
		
		Light light = lightService.queryLightById(deviceId);
		if(light==null) {
			result.put("success", 1);
			result.put("msg", "该设备不存在！");
			this.writeData(result);
			return;
		}
		
		Dtu dtu = dtuService.queryDtuById(light.getDtuId()+"");
		
		LightStatusBean lightStatus = netService.readRtuStatus(dtu.getPanId(), light.getLightNum());
		if(lightStatus==null) {
			result.put("success", 1);
			result.put("msg", "设备状态查看失败，可能因为网络波动，稍后请重试！");
		}else {
			result.put("success", 0);
			result.put("light", light);
			result.put("lightStatus", lightStatus);
		}
		
		this.writeData(result);
	}
	
	@RequestMapping("/readRtuConfig")
	@ResponseBody
	public void readRtuConfig() {
		JSONObject result = new JSONObject();
		String deviceId = this.getValue("deviceId");
		if(ValidateUtil.empty(deviceId)) {
			result.put("success", 1);
			result.put("msg", "该设备不存在！");
			this.writeData(result);
			return;
		}
		
		Light light = lightService.queryLightById(deviceId);
		if(light==null) {
			result.put("success", 1);
			result.put("msg", "该设备不存在！");
			this.writeData(result);
			return;
		}
		
		Dtu dtu = dtuService.queryDtuById(light.getDtuId()+"");
		LightConfig lightConfig = netService.readRtuConfig(dtu.getPanId(), light.getLightNum());
		if(lightConfig!=null) {
			LightConfigBean lightConfigBean = convertConfigToBean(lightConfig);
			result.put("success", 0);
			result.put("lightConfigBean", lightConfigBean);
			result.put("light", light);
		}else {
			result.put("success", 1);
			result.put("msg", "配置读取失败，请重新尝试！");
		}
		
		this.writeData(result);
	}
	
	
	@RequestMapping("/changeLightId")
	@ResponseBody
	public void changeLightId() {
		JSONObject result = new JSONObject();
		String deviceId = this.getValue("deviceId");
		String panIdNew = this.getValue("panIdNew");
		String lightNumNew = this.getValue("lightNumNew");
		if(ValidateUtil.empty(deviceId)) {
			result.put("success", 1);
			result.put("msg", "该设备不存在！");
			this.writeData(result);
			return;
		}
		
		Light light = lightService.queryLightById(deviceId);
		if(light==null) {
			result.put("success", 1);
			result.put("msg", "该设备不存在！");
			this.writeData(result);
			return;
		}
		
		Dtu dtu = dtuService.queryDtuById(light.getDtuId()+"");
		boolean reslut = netService.changeLightId(dtu.getPanId(), light.getLightNum(), panIdNew, lightNumNew);
		if(reslut) {
			dtuService.changePanId(dtu.getDtuId(), panIdNew);
			lightService.changeLightNum(light.getLightId(), lightNumNew);
			result.put("success", 0);
			result.put("msg", "修改成功");
		}else {
			result.put("success", 1);
			result.put("msg", "配置读取失败，请重新尝试！");
		}
		
		this.writeData(result);
	}
	
	private LightConfigBean convertConfigToBean(LightConfig lightConfig) {
		LightConfigBean bean = new LightConfigBean();
		bean.setLightId(lightConfig.getLightId());
		bean.setLightType(lightConfig.getLightType());
		bean.setSerialNum(lightConfig.getSerialNum());
		bean.setProductTime(lightConfig.getProductTime()==null?"":DateUtil.timeFormat(lightConfig.getProductTime()));
		bean.setControlModel(lightConfig.getControlModel());
		bean.setTurnonVol(lightConfig.getTurnonVol()/10.0 + "");
		bean.setTurnonTime(lightConfig.getTurnonTime());
		bean.setShutdownTime(lightConfig.getShutdownTime());
		bean.setWorkModel(lightConfig.getWorkModel());
		bean.setTopVol(lightConfig.getTopVol()/10.0 + "");
		bean.setLowVol(lightConfig.getLowVol()/10.0 + "");
		bean.setExitVol(lightConfig.getExitVol()/10.0 + "");
		bean.setLowStartVol(lightConfig.getLowStartVol()/10.0 + "");
		bean.setLowEndVol(lightConfig.getLowEndVol()/10.0 + "");
		bean.setMaxWorkCurrent(lightConfig.getMaxWorkCurrent());
		bean.setTime1(lightConfig.getTime1());
		bean.setWorkCurrent1(lightConfig.getWorkCurrent1());
		bean.setTime2(lightConfig.getTime2());
		bean.setWorkCurrent2(lightConfig.getWorkCurrent2());
		bean.setTime3(lightConfig.getTime3());
		bean.setWorkCurrent3(lightConfig.getWorkCurrent3());
		bean.setTime4(lightConfig.getTime4());
		bean.setWorkCurrent4(lightConfig.getWorkCurrent4());
		
		return bean;
	}
}
